package com.issac.mailserver.receiver;

import com.issac.vhr.entity.Employee;
import com.issac.vhr.entity.MailConstants;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

@Component
public class DirectMailReceiver {

    public static final Logger logger = LoggerFactory.getLogger(DirectMailReceiver.class);

    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    MailProperties mailProperties;
    @Autowired
    TemplateEngine templateEngine;
    @Autowired
    StringRedisTemplate redisTemplate;

    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
    //Employee employee
    public void MailSendHandler(Message message, Channel channel) throws IOException {
        //拿到message
        Employee employee = (Employee) message.getPayload();
        MessageHeaders messageHeaders = message.getHeaders();
        Long tag = (Long) messageHeaders.get(AmqpHeaders.DELIVERY_TAG);
        //拿到唯一id
        String msgId = (String) messageHeaders.get("spring_returned_message_correlation");
        //存入redis
        if (redisTemplate.opsForHash().entries("mail_log").containsKey(msgId)) {
            //redis中包含该key 说明该消息已被消费过了
            logger.info(msgId + ":该消息已被消费");
            //确认消息 不再回到队列
            channel.basicAck(tag, false);
            return;
        }

        logger.info(employee.toString());
        //收到消息 发送邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
        try {
            mimeMessageHelper.setTo(employee.getEmail());
            mimeMessageHelper.setFrom(mailProperties.getUsername());
            mimeMessageHelper.setSubject("MAIL SERVER  TEST");
            mimeMessageHelper.setSentDate(new Date());
            //渲染模板
            Context context = new Context();/*
            context.setVariable("name",employee.getName());
            context.setVariable("positionName",employee.getPosition().getName());
            context.setVariable("joblevelName",employee.getJobLevel().getName());
            context.setVariable("departmentName",employee.getDepartment().getName());*/
            String mail = templateEngine.process("mailTemplate", context);
            mimeMessageHelper.setText(mail, true);
            javaMailSender.send(mimeMessage);
            redisTemplate.opsForHash().put("mail_log", msgId, "解决mq幂等性");
            channel.basicAck(tag, false);
            logger.info(msgId + ":邮件发送成功");
        } catch (MessagingException e) {
            channel.basicNack(tag,false,true);//标记 回到队列
            e.printStackTrace();
            logger.error("邮件发送失败" + e.getMessage());
        }

    }
}
